package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.AskManageModel;
import com.mtnz.njk.model.AskStatisticsModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 社区提问
 */
@Service
public class AskManageService {
    @Autowired
    AskManageMapper askManageMapper;

    @Autowired
    CalendarMapper calendarMapper;

    @Autowired
    AskManageImgMapper askManageImgMapper;

    @Autowired
    CommentAskManageMapper commentAskManageMapper;

    @Autowired
    CommentAskImgManageMapper commentAskImgManageMapper;

    @Autowired
    NjkUserMapper njkUserMapper;

    @Autowired
    NjkUserInfoMapper njkUserInfoMapper;

    /**
     * 提问列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ResponseResult askList(Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        List<AskManageModel> askEntities = askManageMapper.askAll();
        PageInfo pageInfo = new PageInfo<>(askEntities);
        return new ResponseResult(ResponseMessage.OK,pageInfo);
    }

    /**
     * 查询提问列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ResponseResult checkAskList( String key,Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        List<AskManageModel> askEntities = askManageMapper.checkAskList(key);
        PageInfo pageInfo = new PageInfo<>(askEntities);
        return new ResponseResult(ResponseMessage.OK,pageInfo);
    }

    /**
     * 删除提问
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delAsk(String askId)throws Exception{
        //删除提问
        askManageMapper.deleteByPrimaryKey(askId);
        //删除对应的评论
        Example example = new Example(CommentAskEntity.class);
        example.createCriteria().andEqualTo("askId",askId);
        commentAskManageMapper.deleteByExample(example);
        //删除图片
        Example example1 = new Example(AskImgEntity.class);
        example.createCriteria().andEqualTo("askId",askId);
        askManageImgMapper.deleteByExample(example1);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 评论列表
     * @param askId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */

    public ResponseResult AskCommentList(String askId, Integer pageNum, Integer pageSize)throws Exception{
        //分页
        PageHelper.startPage(pageNum, pageSize);
        Example example10 = new Example(CommentAskEntity.class);
        example10.createCriteria().andEqualTo("askId", askId);
        List<CommentAskEntity> commentAskEntities = commentAskManageMapper.selectByExample(example10);

        for (CommentAskEntity commentAskEntity : commentAskEntities) {
            //获取评论人姓名
            Example example1 = new Example(NjkUserEntity.class);
            example1.createCriteria().andEqualTo("userId", commentAskEntity.getUserId());
            List<NjkUserEntity> njkUserEntities = njkUserMapper.selectByExample(example1);
            for (NjkUserEntity njkUserEntity : njkUserEntities) {
                String name = njkUserEntity.getNickName();
                commentAskEntity.setNickName(name);
            }

            //获取回复人姓名
            Example example2 = new Example(NjkUserEntity.class);
            example2.createCriteria().andEqualTo("userId", commentAskEntity.getReplyId());
            List<NjkUserEntity> njkUserEntities1 = njkUserMapper.selectByExample(example2);
            for (NjkUserEntity njkUserEntity : njkUserEntities1) {
                String name = njkUserEntity.getNickName();
                commentAskEntity.setPName(name);
            }

            //获取用户头像
            Example example3 = new Example(NjkUserInfoEntity.class);
            example3.createCriteria().andEqualTo("userId", commentAskEntity.getUserId());
            List<NjkUserInfoEntity> njkUserInfoEntities = njkUserInfoMapper.selectByExample(example3);
            for (NjkUserInfoEntity njkUserInfoEntity : njkUserInfoEntities) {
                String img = njkUserInfoEntity.getImg();
                commentAskEntity.setImg(img);
            }

        }

        PageInfo pageInfo = new PageInfo<>(commentAskEntities);
        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 删除评论
     * @param commentAskId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult delAskComment(String commentAskId)throws Exception{
        commentAskManageMapper.deleteByPrimaryKey(commentAskId);
        Example example = new Example(CommentAskImgEntity.class);
        example.createCriteria().andEqualTo("commentAskId",commentAskId);
        commentAskImgManageMapper.deleteByExample(example);
        return new ResponseResult(ResponseMessage.OK);
    }


    /**
     * 添加提问评论
     *
     * @return
     */
    @Transactional
    public ResponseResult addCommentAsk(String askId, String userId, String message, String img) {

        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("askId", askId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("img", img);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/commentAsk", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 回复评论
     *
     * @param userId
     * @param askId
     * @param message
     * @param commentAskId
     * @return
     */
    @Transactional
    public ResponseResult commentAskReply(String userId, String askId, String message, String commentAskId) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("askId", askId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("commentAskId", commentAskId);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/replyCommentAsk", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 回复评论回复
     *
     * @param askId 提问
     * @param userId     用户
     * @param message    内容
     * @param pid        上一条回复的ID
     * @return
     */
    @Transactional
    public ResponseResult commentAskReplys(String userId, String askId, String message, String replyId, String pid) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("askId", askId);
        paramMap.put("userId", userId);
        paramMap.put("message", message);
        paramMap.put("replyId", replyId);
        paramMap.put("pid", pid);
        String s = HttpUtil.toParams(paramMap);
        String result = HttpUtil.post("http://localhost:9998/community/replyCommentAsks", s);

        return new ResponseResult(ResponseMessage.OK, result);
    }

    /**
     * 社区提问统计
     * @param startTime
     * @param endTime
     * @param status
     * @return
     * @throws Exception
     */
    public ResponseResult askStatistics(String startTime, String endTime, String status) throws Exception {
        //封装结果
        Map map = new HashMap();
        //判断时间不为空
        if (startTime != null && endTime != null && !"".equals(startTime) && !"".equals(endTime)) {
            //获取时间内的数据
            List<AskStatisticsModel> createDate = askManageMapper.findCreateDate(startTime, endTime);
            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selAskDateAll(startTime, endTime);
            for (CalendarEntity calendarEntity : calendarEntities) {
                //遍历researchStatistics
                for (AskStatisticsModel askStatisticsModel : createDate) {
                    //获取时间
                    String createDate1= askStatisticsModel.getCreateDate();
                    Date date = DateUtil.parse(createDate1);
                    String format1 = DateUtil.format(date, "yyyy-MM-dd");
                    //对比日历的时间
                    if (format1.equals(calendarEntity.getDateList())) {
                        //得到分享数
                        String shareViews = askStatisticsModel.getShareViews();
                        if (shareViews != null && !"".equals(shareViews)) {
                            Integer views = Integer.parseInt(shareViews);
                            calendarEntity.setShareViews(views);
                        }
                        //得到发帖数
                        String countAsk = askStatisticsModel.getCountAsk();
                        if (countAsk != null && !"".equals(countAsk)) {
                            Integer i = Integer.parseInt(countAsk);
                            calendarEntity.setResearchViews(i);
                        }
                    }
                }
                map.put("Statistics", calendarEntities);
            }
        }

        //status是O查询月数据
        if ("0".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();

            //获取当前时间的前一个月
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.MONTH, -1);// 月份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(resultDate);
            Map map1 = askManageMapper.findCreateDateMonth(format, now);
            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selAskAll(format, now);

            for (CalendarEntity calendarEntity : calendarEntities) {
                //获取时间
                Object recover_date = map1.get("create_date");
                String s = recover_date.toString();
                Date date = DateUtil.parse(s);
                String format1 = DateUtil.format(date, "yyyy-MM-dd");
                if (format1.equals(calendarEntity.getDateList())) {
                    //获取分享数
                    Object obj = map1.get("sum(share_views)");
                    String str = obj.toString();
                    if (str != null && !"".equals(str)) {
                        Integer views = Integer.parseInt(str);
                        calendarEntity.setShareViews(views);
                    }
                }
            }

            map.put("Statistics", calendarEntities);
        }

        //status是1查询年数据
        if ("1".equals(status)) {
            //获取当前时间
            //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
            String now = DateUtil.now();
            //获取当前时间的前一年
            Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
            ca.setTime(new Date()); // 设置时间为当前时间
            ca.add(Calendar.YEAR, -1); // 年份减1
            Date resultDate = ca.getTime(); // 结果
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(resultDate);
            //获取这一年时间段的所有帖子，根据帖子创建时间查询每月的发帖数和分享数
            List<AskStatisticsModel> createDateYear = askManageMapper.findCreateDateYear(format, now);

            //日历
            List<CalendarEntity> calendarEntities = calendarMapper.selAskAllYear(format, now);
            for (CalendarEntity calendarEntity : calendarEntities) {
                for (AskStatisticsModel askStatisticsModel : createDateYear) {

                    //获取时间进行对比
                    String createDate = askStatisticsModel.getCreateDate();
                    Date date = DateUtil.parse(createDate);
                    String format1 = DateUtil.format(date, "yyyy-MM");
                    if (format1 == null && "".equals(format1)) {
                        calendarEntity.setShareViews(0);
                        calendarEntity.setResearchViews(0);
                    }
                    String dateList = calendarEntity.getDateList();
                    Date date1 = DateUtil.parse(dateList);
                    String format2 = DateUtil.format(date1, "yyyy-MM");
                    if (format1.equals(format2)) {
                        String shareViews = askStatisticsModel.getShareViews();
                        if (shareViews != null && !"".equals(shareViews)) {
                            Integer views = Integer.parseInt(shareViews);
                            calendarEntity.setShareViews(views);
                        }
                        String countAsk = askStatisticsModel.getCountAsk();
                        if (countAsk != null && !"".equals(countAsk)) {
                            calendarEntity.setResearchViews(Integer.parseInt(countAsk));
                        }
                    }
                    calendarEntity.setYear(format2);
                }
            }
            map.put("Statistics", calendarEntities);
        }
        return new ResponseResult(ResponseMessage.OK,map);
    }


}
